const { executeSql, sqlEscape } = require('../utils/mysql')

module.exports = {
  orderListDB: async (user) => {
    const userSql = +user.state > 1
      ? ''
      : `and (sender_name = '${user.username}' or receiver_name = '${user.username}')`

    const sql = `select * from orders where state >= 1 ${userSql}
      order by code desc;`
    return await executeSql(sql)
  },
  orderCreateDB: async (order) => {
    const { senderName, senderPhone, senderAddress, 
      receiverName, receiverPhone, receiverAddress, code } = sqlEscape(order)
    const sql = `insert into orders (sender_name, sender_phone, sender_address, 
        receiver_name, receiver_phone, receiver_address, code) 
        values (${senderName}, ${senderPhone}, ${senderAddress}, 
          ${receiverName}, ${receiverPhone}, ${receiverAddress}, ${code});`
    return await executeSql(sql)
  },
  orderDetailDB: async (id, user) => {
    const userSql = +user.state > 1
      ? ''
      : `and (sender_name = '${user.username}' or receiver_name = '${user.username}')`

    id = sqlEscape(id)
    const sql = `select * from orders where id = ${id} and state >= 1 ${userSql};`
    return await executeSql(sql)
  },
  orderDeleteDB: async (id, user) => {
    const userSql = +user.state > 1
      ? ''
      : `and (sender_name = '${user.username}' or receiver_name = '${user.username}')`

    id = sqlEscape(id)
    const sql = `update orders set state = 0
        where id = ${id} ${userSql};`
    return await executeSql(sql)
  },
  orderUpdateState: async (orderId, user, state) => {
    const userSql = (+user.state === 3 || state !== 4)
      ? ''
      : `and receiver_name = '${user.username}'`

    const sql = `update orders set state = ${sqlEscape(state)}
        where id = ${sqlEscape(orderId)} ${userSql};`
    console.log(sql)
    return await executeSql(sql)
  }
}